const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const { pool } = require('../db');

// 获取所有用户
router.get('/', async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT id, username, name, email, role, status, created_at, updated_at FROM users ORDER BY created_at DESC'
    );
    
    res.json({
      success: true,
      data: rows,
      total: rows.length
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      error: '获取用户列表失败'
    });
  }
});

// 根据 ID 获取用户
router.get('/:id', async (req, res) => {
  try {
    const id = parseInt(req.params.id);
    const [rows] = await pool.execute(
      'SELECT id, username, name, email, role, status, created_at, updated_at FROM users WHERE id = ?',
      [id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      data: rows[0]
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      success: false,
      error: '获取用户信息失败'
    });
  }
});

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        error: '用户名和密码不能为空'
      });
    }
    
    // 查询用户
    const [rows] = await pool.execute(
      'SELECT id, username, name, email, role, password, status FROM users WHERE username = ?',
      [username]
    );
    
    if (rows.length === 0) {
      return res.status(401).json({
        success: false,
        error: '用户名或密码错误'
      });
    }
    
    const user = rows[0];
    
    // 检查用户状态
    if (user.status !== 'active') {
      return res.status(401).json({
        success: false,
        error: '账户已被禁用'
      });
    }
    
    // 验证密码
    const hashedInputPassword = crypto.createHash('sha256').update(password).digest('hex');
    const isPasswordValid = hashedInputPassword === user.password;
    
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        error: '用户名或密码错误'
      });
    }
    
    // 更新最后登录时间
    await pool.execute(
      'UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [user.id]
    );
    
    res.json({
      success: true,
      data: {
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          email: user.email,
          role: user.role
        },
        token: 'jwt-token-' + Date.now() // 实际项目中应该使用JWT
      },
      message: '登录成功'
    });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      success: false,
      error: '登录失败'
    });
  }
});

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, name, email, password } = req.body;
    
    if (!username || !name || !email || !password) {
      return res.status(400).json({
        success: false,
        error: '所有字段都是必填的'
      });
    }
    
    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    );
    
    if (existingUsers.length > 0) {
      return res.status(400).json({
        success: false,
        error: '用户名或邮箱已存在'
      });
    }
    
    // 加密密码
    const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
    
    // 插入新用户
    const [result] = await pool.execute(
      'INSERT INTO users (username, name, email, password, role, status) VALUES (?, ?, ?, ?, ?, ?)',
      [username, name, email, hashedPassword, 'user', 'active']
    );
    
    const newUserId = result.insertId;
    
    // 获取新创建的用户信息
    const [newUser] = await pool.execute(
      'SELECT id, username, name, email, role, status, created_at FROM users WHERE id = ?',
      [newUserId]
    );
    
    res.status(201).json({
      success: true,
      data: newUser[0],
      message: '用户注册成功'
    });
  } catch (error) {
    console.error('用户注册失败:', error);
    res.status(500).json({
      success: false,
      error: '用户注册失败'
    });
  }
});

// 更新用户信息
router.put('/:id', async (req, res) => {
  try {
    const id = parseInt(req.params.id);
    const { name, email, role, status } = req.body;
    
    // 检查用户是否存在
    const [existingUser] = await pool.execute(
      'SELECT id FROM users WHERE id = ?',
      [id]
    );
    
    if (existingUser.length === 0) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      });
    }
    
    // 检查邮箱是否被其他用户使用
    if (email) {
      const [emailCheck] = await pool.execute(
        'SELECT id FROM users WHERE email = ? AND id != ?',
        [email, id]
      );
      
      if (emailCheck.length > 0) {
        return res.status(400).json({
          success: false,
          error: '邮箱已被其他用户使用'
        });
      }
    }
    
    // 更新用户信息
    await pool.execute(
      'UPDATE users SET name = ?, email = ?, role = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [name, email, role, status, id]
    );
    
    // 获取更新后的用户信息
    const [updatedUser] = await pool.execute(
      'SELECT id, username, name, email, role, status, created_at, updated_at FROM users WHERE id = ?',
      [id]
    );
    
    res.json({
      success: true,
      data: updatedUser[0],
      message: '用户信息更新成功'
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({
      success: false,
      error: '更新用户信息失败'
    });
  }
});

// 删除用户
router.delete('/:id', async (req, res) => {
  try {
    const id = parseInt(req.params.id);
    
    // 检查用户是否存在
    const [existingUser] = await pool.execute(
      'SELECT id, username, name FROM users WHERE id = ?',
      [id]
    );
    
    if (existingUser.length === 0) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      });
    }
    
    // 删除用户
    await pool.execute('DELETE FROM users WHERE id = ?', [id]);
    
    res.json({
      success: true,
      data: existingUser[0],
      message: '用户删除成功'
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({
      success: false,
      error: '删除用户失败'
    });
  }
});

// 修改密码接口
router.post('/change-password', async (req, res) => {
  try {
    const { username, oldPassword, newPassword } = req.body;
    
    if (!username || !oldPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        error: '用户名、原密码和新密码不能为空'
      });
    }
    
    // 查询用户
    const [rows] = await pool.execute(
      'SELECT id, password FROM users WHERE username = ?',
      [username]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      });
    }
    
    const user = rows[0];
    
    // 验证原密码
    const hashedOldPassword = crypto.createHash('sha256').update(oldPassword).digest('hex');
    const isOldPasswordValid = hashedOldPassword === user.password;
    
    if (!isOldPasswordValid) {
      return res.status(401).json({
        success: false,
        error: '原密码错误'
      });
    }
    
    // 加密新密码
    const hashedNewPassword = crypto.createHash('sha256').update(newPassword).digest('hex');
    
    // 更新密码
    await pool.execute(
      'UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [hashedNewPassword, user.id]
    );
    
    res.json({
      success: true,
      message: '密码修改成功'
    });
  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({
      success: false,
      error: '修改密码失败'
    });
  }
});

module.exports = router; 